package net

import (
	"github.com/panjf2000/gnet"
	"log"
	"strings"
	"time"
)

type Server struct {
	*gnet.EventServer
	Addr      string
	Multicore bool
}

func (es *Server) OnInitComplete(srv gnet.Server) (action gnet.Action) {
	log.Printf("tcp server is listening on %s (multi-cores: %t, loops: %d)\n",
		srv.Addr.String(), srv.Multicore, srv.NumEventLoop)
	return
}

func (es *Server) React(frame []byte, c gnet.Conn) (out []byte, action gnet.Action) {

	log.Println("接收到数据：", string(frame))

	// 异常捕获
	defer func() {
		if err := recover(); err != nil {
			log.Println("程序异常：", err)
		}
	}()

	slice := strings.Split(string(frame), "\r\n")

	for _, v := range slice {
		if len(v) > 0 {
			handleData(v)
		}
	}

	return nil, gnet.None
}

// 处理数据
func handleData(data string) {
	// 根据 "," 分割
	list := strings.Split(strings.TrimRight(data, "\n"), ",")
	//loc, _ := time.LoadLocation("Asia/Shanghai")
	if len(data) <= 2 {
		return
	}
	if len(list[1]) == 1 {
		times := list[13] + " " + list[14]

		parseObj, _ := time.Parse("2006/01/02 15:04:05", times)
		device := NewDevice()
		device.Number = list[0]
		device.Time = parseObj.Unix()
		device.Rev = ""
		device.FuelConsumption = list[2]
		device.ManHour = list[3]
		device.IdlingFuelConsumption = list[4]
		device.IdlingManHour = list[5]
		device.Lng = list[10]
		device.Lat = list[12]
		device.Date = parseObj.Format("2006-01-02")
		device.DateTime = parseObj.Format("2006-01-02 15:04:05")
		device.UserId = ""
		device.ErrorCount = ""
		device.Average = ""
		device.Mileage = ""
		device.OilIn = list[6]
		device.OilOf = list[7]
		device.Error = list[8]
		device.AddTime = time.Now().Format("2006-01-02 15:04:05")
		device.Send()
	} else {
		date := list[1]
		parseObj, err := time.Parse("2006/01/02", date)
		parseDate := parseObj.Format("2006-01-02")
		if err != nil {
			log.Println("时间解析错误:", err.Error())
			return
		}
		device := NewShortDevice(list[0], list[2], list[3], list[4], list[5], parseDate)
		device.Send()
	}

}
